//
//  SZHomeTableVC.swift
//  WeiBoExercise
//
//  Created by lx on 16/9/19.
//  Copyright © 2016年 BeiWo. All rights reserved.
//

import UIKit

class SZHomeTableVC: SZCommentTableVC {

    var titleButton : UIButton?
    
    
    var homePageModelsArr : [SZHomePageModel]?
    {
        
        didSet
        {
        
            tableView.reloadData()
        }
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "popoverStatusChange:", name: ClickPopoverView, object:nil)
        
        
        //加载首页表视图的时候就说明已经登录了，我们应该进行相关微博信息的请求了。
        
        //这里加上判断的原因是，我们在性特性页面进入未登录页面的时候，虽然我们这个类继承自SZCommentTableVC,我们在里面覆写了loadView方法，但是loadView方法走完还是会走这个方法的，所以如果没有判断的话后面的请求就拿不到用户信息中请求微博内容的有关参数，会崩溃。
        if SZAccountModel.loadAccount()?.access_token != nil
        {
            
            _loadNetworkData()

        }
        
        
        
//        //注册单元格
//        tableView.registerNib(UINib.init(nibName: "SZHomePageCell", bundle: nil), forCellReuseIdentifier: "")

        //设置分割线颜色
        tableView.separatorColor = UIColor.clearColor()
        
        
    }

    //请求网络数据
    func _loadNetworkData()
    {
    
        SZHomePageModel.loadHomePageData { (modelsArr, error) -> () in
            
            if error == nil && modelsArr != nil
            {
                
                self.homePageModelsArr = modelsArr

            }
            else
            {
                print("微博数据加载错误!!")
            }
            
            
        }
        
    }
    
    
    override func viewWillAppear(animated: Bool)
    {
        
        super.viewWillAppear(animated)
        
        
        //说明不是登录状态
        if !isLoginStatus
        {
        
            let notLoginView = view as! SZNotLoginView
            notLoginView.isHomePage = TabBarIndex.HomePage
//            print(notLoginView)
            
            navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: "registerOrMoreBtnClicked:")
            
            navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: UIBarButtonItemStyle.Plain, target: self, action: "loginBtnClicked")
            
            
        }
        else
        {
        
            //左边
            navigationItem.leftBarButtonItem = UIBarButtonItem.createBarButtonItem("navigationbar_friendattention", target: self, action: "friendsAction:")
            
            //右边
            navigationItem.rightBarButtonItem = UIBarButtonItem.createBarButtonItem("navigationbar_pop", target: self, action: "QRAction:")
            
            
            let titleBtn = TitleButton()
            titleBtn.setTitle("我的微博", forState: .Normal)
            //事件添加
            titleBtn.addTarget(self, action: "popoverViewAction:", forControlEvents: .TouchUpInside)
            
            titleButton = titleBtn
            
            navigationItem.titleView = titleButton
            
        
        }
        
        
    }
    
    
    //MARK: -通知调用方法
    func popoverStatusChange(notification:NSNotification)
    {
    
        let userInfo = notification.userInfo!
        
        let isPresent  = userInfo["isPresent"]!
        
        if isPresent as! String == "true"
        {
            print("popover出现了")
            titleButton?.selected = true
            
        }
        else
        {
        
            print("popover消失了")
            titleButton?.selected = false
            
        }
    }
    
    //MARK: -移除通知
    deinit
    {
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
    //MARK: -按钮点击事件
    func friendsAction(sender : UIButton)
    {
    
        print("点击了用户按钮")
    }
    
    
    
    
    func QRAction(sender : UIButton)
    {
    
        print("点击了扫描二维码按钮")
        let storyBoard : UIStoryboard = UIStoryboard(name: "QRCodeVC", bundle: NSBundle.mainBundle())
        let qrNaviVC = storyBoard.instantiateInitialViewController()
        
//        qrNaviVC?.navigationController?.navigationBar.barTintColor = UIColor.init(white: 0, alpha: 0.1)
        self.navigationController?.presentViewController(qrNaviVC!, animated: true, completion: { () -> Void in
            
        })

        
        
    }
    
    
    
    func popoverViewAction(sender : UIButton)
    {
    
        print("点击了popover按钮")
        
        print("点击了扫描二维码按钮")
        let storyBoard : UIStoryboard = UIStoryboard(name: "Popover", bundle: NSBundle.mainBundle())
        let popoverVC = storyBoard.instantiateInitialViewController()
        
        popoverVC?.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        popoverVC?.transitioningDelegate = popoverHelp
        
        
        self.presentViewController(popoverVC!, animated: true) { () -> Void in
            
        }
        
        
    }
    
    
    //MARK: - 懒加载创建 
    private lazy var popoverHelp : SZPopoverHelp = {
        
        
        let popoverTool = SZPopoverHelp()
        //popoverTool.newFrame = CGRectMake()
        
        return popoverTool
        
    }()
    

    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {

        
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return homePageModelsArr?.count ?? 0
    }

    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        

        let resueCellID : String = "resueCellID"
        
        var cell = tableView.dequeueReusableCellWithIdentifier(resueCellID)
        let model = homePageModelsArr![indexPath.row]

        let homePageCell : SZHomePageCell?
        
        if cell == nil
        {
        
            cell = NSBundle.mainBundle().loadNibNamed("SZHomePageCell", owner: self, options: nil).first as! SZHomePageCell
            
        }
        
        homePageCell = cell! as? SZHomePageCell

        homePageCell?.model = model
        
        return homePageCell!
    }

    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        return 300.0
        
    }
    

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        
    }
    
    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
